/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import com.ezware.oxbow.swingbits.table.filter.TableRowFilterSupport;
import dataentry.EditValues;
import dataentry.Persistence;
import dataentry.SaveChanges;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author i.capurro
 */
public class Edit extends javax.swing.JFrame {

    private HashMap edit = null;
    private List del = null;
    private String tname = null;
    
    /**
     * Creates new form Edit
     */
    
    Action delete = new AbstractAction()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {   
            try {
                JTable table = (JTable)e.getSource();
                int modelRow = Integer.valueOf( e.getActionCommand() );
                int id = (int) table.getModel().getValueAt(modelRow, 0);
                del.add(id);
                ((DefaultTableModel)table.getModel()).removeRow(modelRow);
            } catch (Exception ex) {
                Logger.getLogger(Edit.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };
    
    Action action = new AbstractAction()
    {
        public void actionPerformed(ActionEvent e)
        {
            TableCellListener tcl = (TableCellListener)e.getSource();
            int id = (int) table.getModel().getValueAt(tcl.getRow(), 0);
            EditValues ed = (EditValues) edit.get(id);
            
            if (ed != null) {
                ed.insertValue(table.getColumnName(tcl.getColumn()-1), (String) tcl.getNewValue());
                edit.remove(id);
                edit.put(id, ed);
            } else {
                ed = new EditValues(id);
                ed.insertValue(table.getColumnName(tcl.getColumn()-1), (String) tcl.getNewValue());
                edit.put(id, ed);
            }
        }
    };
    
    public Edit() {
       initComponents();
       ImageIcon icon = new ImageIcon("icon.png", "icon");
       this.setIconImage(icon.getImage());
       this.setTitle("RDE Respuestas");
    }
    
    public void setTableName(String name) {
        try {
            this.tname = name;
            this.setTitle("Respuestas " + name);
            edit = new HashMap();
            del = new ArrayList();
            DefaultTableModel tmodel = new DefaultTableModel();
            Persistence p = Persistence.getInstance();
            List header = p.getTableHeader(name);
            Iterator ith = header.iterator();
            while (ith.hasNext()) {
                tmodel.addColumn(ith.next());
            }
            tmodel.addColumn("Borrar"); // columna borrar
            
            List data = p.getTableData(name);
            
            Iterator itd = data.iterator();
            
            while (itd.hasNext()) {
                List aux = (List) itd.next();
                Iterator itaux = aux.iterator();
                Vector v = new Vector();
                while (itaux.hasNext()) {
                    v.add(itaux.next());
                }
                v.add("borrar"); // boton de borrar
                tmodel.addRow(v);
            }
            
            
            table.setModel(tmodel);
            TableRowFilterSupport.forTable(table).apply();

            TableColumn column = null;
            for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
                column = table.getColumnModel().getColumn(i);
                column.setMinWidth(60);
            }
            
            ButtonColumn buttonColumn1 = new ButtonColumn(table, delete, table.getColumnModel().getColumnCount()-1);
            
            TableCellListener tcl = new TableCellListener(table, action);
            
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            
            FixedColumnTable fct = new FixedColumnTable(1, scroll);
                        
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
            JOptionPane.showMessageDialog(null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jToolBar2 = new javax.swing.JToolBar();
        jButton2 = new javax.swing.JButton();
        scroll = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jToolBar2.setRollover(true);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/Save.png"))); // NOI18N
        jButton2.setToolTipText("Guardar");
        jButton2.setBorderPainted(false);
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jToolBar2.add(jButton2);

        scroll.setAutoscrolls(true);

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        table.setColumnSelectionAllowed(true);
        table.getTableHeader().setReorderingAllowed(false);
        scroll.setViewportView(table);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addComponent(scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 658, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scroll, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        if (!del.isEmpty() || !edit.isEmpty()) {
            int confirmado = JOptionPane.showConfirmDialog(this,"¿Desea guardar los cambios?");
            if (JOptionPane.OK_OPTION == confirmado) {
                try {
                    SaveChanges sc = new SaveChanges(tname, edit, del);
                    sc.save();
                    dispose();
                } catch (        ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
                    JOptionPane.showMessageDialog( null, ex);
                }
            } else if ((JOptionPane.NO_OPTION == confirmado)) {
                dispose();
            }
        } else {
            dispose();
        }
    }//GEN-LAST:event_formWindowClosing

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {
            SaveChanges sc = new SaveChanges(tname, edit, del);
            sc.save();
            edit.clear();
            del.clear();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
            JOptionPane.showMessageDialog(null, ex);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Edit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Edit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Edit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Edit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Edit().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JScrollPane scroll;
    private javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables
}
